package com.windoent.yugioh.ui.fragment.saishi.shouye;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.MyApplication;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.SaiShiHomePageAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.SaiShiListDataBean;
import com.windoent.yugioh.bean.eventbus.SaiShiMessageEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.JumpHelper;
import com.windoent.yugioh.ui.activity.saishi.GameActivity;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/14 17:31
 * desc   :进行中(3)
 */
public class HomeOnGoingFragment extends BaseFragment {
    private SmartRefreshLayout mSmartLayout;
    private RecyclerView mRecyclerView;
    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private SaiShiHomePageAdapter adapter;
    private String status = "3";//3
    ;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_page_ongoing;
    }

    public static HomeOnGoingFragment newsInstance() {
        return new HomeOnGoingFragment();
    }

    @Override
    protected void initEventAndData() {
        EventBus.getDefault().register(this);
        initView();
        initData();
        initListener();
    }

    private void initData() {
        initAdapter();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "赛事进行中tab");
        }
        initRefreshData(MyApplication.slectShai, MyApplication.cityCode);
        fresh(MyApplication.slectShai, MyApplication.cityCode);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "赛事进行中tab");
        }
    }

    private void initListener() {

    }

    private void initView() {
        mSmartLayout = (SmartRefreshLayout) mView.findViewById(R.id.smart_layout);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
    }

    private void initRefreshData(String type, String code) {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(type, code);
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore(type, code);
            }
        });
    }

    private void loadMore(String type, String code) {
        mCount = mCount + 1;
        getSaiShiHomepageList(type, mCount + "", limit, code, false);
    }

    private void fresh(String type, String code) {
        mCount = 1;
        getSaiShiHomepageList(type, mCount + "", limit, code, true);
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new SaiShiHomePageAdapter();
        adapter.setAnimationEnable(false);
        adapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.recycler_view_empty, mRecyclerView, false));
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                if (BaseMethod.isNull(getUserToken())) {
                    BaseUtils.toLogIn(mContext, "");
                    return;
                }
                //
                List<SaiShiListDataBean.DataBean.MatchsBean> data = adapter.getData();
                if (data != null) {
                    SaiShiListDataBean.DataBean.MatchsBean matchsBean = data.get(position);
                    int id = matchsBean.getId();
                    int rule = matchsBean.getRule();
                    JumpHelper.startGameTab(mContext, id + "",rule+"");
                }
            }
        });
    }

    //赛事列表
    private void getSaiShiHomepageList(String type, String page, String limit, String code, boolean fresh) {
        showLoadingDialog("");
        PhoneLive.getSaiShiHomeListData(getUserToken(), type, status, page, limit, code, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(fresh);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            SaiShiListDataBean json = gson.fromJson(response, SaiShiListDataBean.class);
                            SaiShiListDataBean.DataBean data = json.getData();
                            if (data != null) {
                                List<SaiShiListDataBean.DataBean.MatchsBean> matchs = data.getMatchs();
                                if (matchs != null && matchs.size() > 0) {
                                    if (fresh) {
                                        adapter.setNewInstance(matchs);
                                        mSmartLayout.finishRefresh(true);
                                    } else {
                                        adapter.addData(matchs);
                                        mSmartLayout.finishLoadMore(true);
                                    }
                                } else freshFail(fresh);
                            } else freshFail(fresh);
                        } else freshFail(fresh);
                    } catch (JSONException e) {
                        freshFail(fresh);
                        e.printStackTrace();
                    }
                } else {
                    freshFail(fresh);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //刷新失败
    private void freshFail(boolean fresh) {
        ToastUtils.showText(getString(R.string.string_no_data));
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(SaiShiMessageEvent event) {
        String message = event.getMessage();
        String code = event.getCode();
        int type = event.getType();
        if (type == 1) {
            initRefreshData(message, code);
            fresh(message, code);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //解除注册EventBus
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
    }
}
